<template>
  <section>
    <h2>学生列表</h2>
    <el-table :data="computedList" style="width: 100%" ref="multipleTableRef">
      <el-table-column width="55">
        <template #default="scope">
          <input type="checkbox" v-model="selectIds" :value="scope.row.id" />
        </template>
      </el-table-column>
      <el-table-column prop="name" label="姓名" width="180" />
      <el-table-column prop="tel" label="电话" width="180" />
      <el-table-column prop="sex" label="性别" />
      <el-table-column>
        <template #default="scope">
          <el-button
            size="small"
            type="danger"
            @click="handleDeleteRow(scope.row.id)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <div class="tfoot">
      <span class="span-type">{{ leftCount }}未选</span>
      <span @click="handleType(1)" :class="getClass(1)">全部</span>
      <span @click="handleType(2)" :class="getClass(2)">未选中</span>
      <span @click="handleType(3)" :class="getClass(3)">选中</span>
      <span @click="handleDelete" class="span-type">删除选中</span>
    </div>
  </section>
</template>

<script lang="ts" setup>
import { ref, computed, defineProps, defineEmits } from "vue";
import { ElTable } from "element-plus";

const multipleTableRef = ref<InstanceType<typeof ElTable>>();

const props = defineProps({
  listData: {
    type: Array,
    required: true,
  },
});

const emits = defineEmits(["delete-row", "delete"]);

// 选中的项目
const type = ref(1);
const selectIds = ref([]);

// 点击行后面的删除，删除当前行
function handleDeleteRow(id: number) {
  emits("delete-row", id);

  // 把存储选中项的也删除
  const index = selectIds.value.findIndex((v) => v == id);
  if (index != -1) {
    selectIds.value.splice(index, 1);
  }
}

function getClass(value: number) {
  return {
    // 当对象的属性值为true的时候，表示有该属性名的class值
    "span-type-active": type.value == value,
    "span-type": true,
  };
}

function handleType(value: number) {
  type.value = value;
}

function handleDelete() {
  // 触发自定义事件，让父组件完成删除
  emits("delete", selectIds.value);

  // 把selectIds也清空
  selectIds.value.length = 0;
}

const computedList = computed(() => {
  // console.log("selectIds = ",selectIds);
  switch (type.value) {
    // 选中
    case 3: {
      return props.listData.filter(
        (v1: any) => selectIds.value.findIndex((v2) => v2 == v1.id) != -1
      );
    }
    // 未选中
    case 2: {
      return props.listData.filter(
        (v1: any) => selectIds.value.findIndex((v2) => v2 == v1.id) == -1
      );
    }
    default:
      return props.listData;
  }
});

const leftCount = computed(
  () => props.listData.length - selectIds.value.length
);
</script>

<style scoped lang="scss">
.tfoot {
  .span-type {
    padding: 5px;
  }

  .span-type-active {
    color: #fff;
    background-color: #ac1111;
  }
}
</style>